import { AxiosResponse } from 'axios'
import { App } from 'vue'
import request from './axios.config'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import LayoutStore from '@/layouts'
import Cookies from 'js-cookie'
import { ROLE_ID_KEY, USER_ID_KEY, USER_INFO_KEY, USER_TOKEN_KEY } from '@/store/keys'
export interface HttpOption {
	url: string
	data?: any
	method?: string
	headers?: any
	beforeRequest?: () => void
	afterRequest?: () => void
}

export interface Response<T = any> {
	code: number
	msg?: string
	data?: T
	action?:string
	url?:string
}
const router = useRouter()
const route =useRoute()
function http<T = any>({ url, data, method, headers, beforeRequest, afterRequest }: HttpOption) {
	const successHandler = (res: AxiosResponse<Response<T>>) => {
		const { code, msg } = res.data;
		if (res.data.code === 200) {
			return res.data
		}

		let  flag = false
		if (res.data.code === 202 || msg === '未找到用户信息') {
			// 清空本地存储的 token 和用户信息
			Cookies.remove(USER_TOKEN_KEY)
			localStorage.clear()
			LayoutStore.reset()
			// 提示用户登录已超时
			flag  = true
			ElMessage.error('登录超时，请重新登录');
			setTimeout(()=>{
				location.reload();
			},1000)
		  }
		  
		//   if (code === 400) {
		// 	// 显示错误提示框或在页面上展示错误信息
		// 	ElMessage.error(`${msg}`);
		//   } 
		if(!flag)ElMessage.error(`${msg || res.data?.msg }`);
		  
		  throw new Error(res.data?.msg  || msg ||'请求失败，未知异常');
	}
	const failHandler = (error: Response<Error>) => {
		afterRequest && afterRequest()
		throw new Error(error.msg || '请求失败，未知异常')
	}
	beforeRequest && beforeRequest()
	method = method || 'GET'
	const params = Object.assign(typeof data === 'function' ? data() : data || {}, {})
	return method === 'GET' ? request.get(url, { params }).then(successHandler, failHandler) : request.post(url, params, { headers: headers }).then(successHandler, failHandler)
}

export function get<T = any>({ url, data, method = 'GET', beforeRequest, afterRequest }: HttpOption): Promise<Response<T>> {
	return http<T>({
		url,
		method,
		data,
		beforeRequest,
		afterRequest
	})
}

export function post<T = any>({ url, data, method = 'POST', headers, beforeRequest, afterRequest }: HttpOption): Promise<Response<T>> {
	return http<T>({
		url,
		method,
		data,
		headers,
		beforeRequest,
		afterRequest
	})
}

function install(app: App): void {
	app.config.globalProperties.$http = http

	app.config.globalProperties.$get = get

	app.config.globalProperties.$post = post
	if (typeof window !== 'undefined') {
		window.onload = function() {
		  const urlParams = new URLSearchParams(window.location.search);
		  const redirectParam = urlParams.get('redirect');
		  if (redirectParam) {
			// 清除重定向地址
			window.history.replaceState({}, document.title, window.location.pathname);
		  }
		};
	  }
}

export default {
	install,
	get,
	post
}

declare module 'vue' {
	// 为 `this.$` 提供类型声明
	interface ComponentCustomProperties {
		$get: <T>(options: HttpOption) => Promise<Response<T>>
		$post: <T>(options: HttpOption) => Promise<Response<T>>
	}
}
